﻿using System;
using System.Web;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.Data;
using System.Collections.Generic;
using System.Net;
using System.Net.NetworkInformation;
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. 
// [System.Web.Script.Services.ScriptService]

//Contains all functions that serve Client, such as Check attendence for user, or export data to website
public class Service : System.Web.Services.WebService
{
    //initialize  a user object
    //view all about user at user.cs
    User user;
    //initialize a Userservice object
    UserService serviceForUser = new UserService();
    //initialize a HAInfoService object
    //view all about serviceForHainfo at HaInfoService.cs
    HAInfoService serviceForHainfo = new HAInfoService();
    
    /// <summary>
    /// contructor
    /// </summary>
    public Service()
    {

        //InitializeComponent(); 
    }
    
    //Web method for user login, it's not necessary now
    [WebMethod(Description = "User login")]   
    public bool UserLogin(String strUserName, String strPassWord)
    {
        return true;
    }

    /// <summary>
    /// Browse all network interface to return right mac address
    /// </summary>
    /// <returns>Mac Address</returns>
    public String GetCurrentMacAddress()
    {
        //return Mac address when connected by Wifi
        foreach (NetworkInterface ni in NetworkInterface.GetAllNetworkInterfaces())
        {   //Gets the current operational state of the network connection.
            //and check the network interface is up; it can transmit data packets.
            if (ni.OperationalStatus == OperationalStatus.Up &&
                //and check if the network interface is unable to transmit data packets because of a missing
                //component, typically a hardware component.
                    ni.OperationalStatus != OperationalStatus.NotPresent &&
                //Check if the network interface uses a tunnel connection.
                //if yes, we can't get Mac address
                        ni.NetworkInterfaceType != NetworkInterfaceType.Tunnel &&
                //Check if the network interfacs is a loopback adapter.
                //if yes, it's just for testing; no traffic is sent.
                            ni.NetworkInterfaceType != NetworkInterfaceType.Loopback &&
                //The network interface uses a wireless LAN connection (IEEE 802.11 standard).
                                    ni.NetworkInterfaceType == NetworkInterfaceType.Wireless80211)
            {
                //return mac address
                return ni.GetPhysicalAddress().ToString();
            }
            //return mac address when connected by Ethernet
            if (ni.NetworkInterfaceType == NetworkInterfaceType.Ethernet &&
                //Gets the current operational state of the network connection.
                //and check the network interface is up; it can transmit data packets.
                    ni.OperationalStatus == OperationalStatus.Up)
            {
                //return mac address
                return ni.GetPhysicalAddress().ToString();
            }
        }
        //if there's no mac address, return NULL
        return null;
    }

    /// <summary>
    /// use to check attendance
    /// </summary>
    /// <param name="userName">user name of user</param>
    /// <param name="MAC">Mac address of user</param>
    /// <returns>
    /// Check attendance for user, with each value returned, we will know status of user
    /// </returns>
    [WebMethod(Description = "Get information of user to check log")]
    public int GetUser(String strUserName, string strMACAddress)
    {
        try
        {
            //assign ID with correspond username
            long logID = serviceForHainfo.GetUserId(strUserName);
            //ID > 0, mean that survive user in Database
            if (logID > 0)
            {
                //initializes a user with that ID and username
                user = new User(logID, strMACAddress);
                //initializes a userservice with above user to carries out tasks
                serviceForUser = new UserService(user);
                //Check if user was checked at current day
                //If user has been checked
                if (serviceForUser.IsUserChecked())
                {
                    //return  0 to client for making a balloon show that user's checked
                    return 0;

                }
                //if user has been not checked
                else
                {
                    //if insert into database successful
                    if (serviceForUser.InsertNewRow())
                    {
                        //update database
                        serviceForUser.UpdateDataBase();
                        //return 1 show that user has just checked attendence successful 
                        return 1;

                    }
                    //else if user has not checked current day, but can't be marked as checked
                    else
                    {
                        return -1;
                    }

                }
            }
            //If ID < 0, show that in database has no that name
            else
            {
                return 2;
            }
        }
        catch
        {
            //can't insert data into database
            return -1;

        }
    }


    /// <summary>
    /// get all users that has current org is HCD
    /// </summary>
    /// <returns></returns>
    [WebMethod(Description = "Get all user at RTD(ID, name, Username, batch)")]
    public DataTable GetAllUsersAtRtd()
    {
        //initializes a datatable to hold returned table
        DataTable dtAllUsers = new DataTable();
        dtAllUsers = serviceForHainfo.GetUsersAtRtd();
        //Set table name
        dtAllUsers.TableName = "USeratRTD";
        //return data table
        return dtAllUsers;
    }

    /*
     * input: User account and the specific day
     * return: Atable has 1 row content:Useraccout, Status, Timelog, MACAddress, Note
     * Require database has tabble Person and PersonDailyLog Inner join on Person.ID
     * */
    /// <summary>
    /// Get detail information of a user in a date
    /// </summary>
    /// <param name="nameOfUser"></param>
    /// <param name="day"></param>
    /// <returns></returns>
    [WebMethod(Description = "Get user’s information detail in specific day(username, status, time, MAC address, Note)")]
    public DataTable GetUserInfoDetailInDay(String strUserName, DateTime dtmDate)

    {
        //initializes a datatable
        DataTable dtDayInfo = new DataTable();
        //set name for table
        dtDayInfo.TableName = "GetUserInfoDetailInDay";
        /*
         *Add Columeto table, it contains information of user in a date
         */
        dtDayInfo.Columns.Add("Username");
        dtDayInfo.Columns.Add("status");
        dtDayInfo.Columns.Add("time");
        dtDayInfo.Columns.Add("MACaddress");
        dtDayInfo.Columns.Add("Note");
        //Check if username available
        long lId = serviceForHainfo.GetUserId(strUserName);
        //If has a ID of current user name
        if(lId>0)
        {
            //Add new row to table with correspond properties column
            DataRow newRow = dtDayInfo.NewRow();
            //add name column
            newRow["Username"] = strUserName;
            //add default status
            newRow["status"] = "Absence";
            //add time, default is nothing 
            newRow["time"] = "";
            //add MAC address,default is nothing
            newRow["MACaddress"] = "";
            //add note, default is nothing
            newRow["note"] = "";
            //Get data from Dataset and assign it to rows (with personID-fitler)
            DataRow[] rows = serviceForUser.GetDataset().Tables[0].Select("personid = '" + lId + "'");
            //if there's items
            if (rows.Length > 0)
            {
                //browse all rows, with each item, do
                foreach (DataRow r in rows)
                {
                    //initializes a datetime object
                    DateTime dtmTimeLog = new DateTime();
                    //try to convert a string to datetime type
                    //convert timelog in row into variable named timelog
                    //return success or fail
                    bool bTryParse = DateTime.TryParse(r["timelog"].ToString(), out dtmTimeLog);
                    //if success
                    if (bTryParse)
                    {
                        //it's that day
                        if (dtmTimeLog.DayOfYear == dtmDate.DayOfYear && dtmTimeLog.Year == dtmDate.Year)
                        {
                            //add Present to status
                            newRow["status"] = "Present";
                            //add timelog to time
                            newRow["time"] = dtmTimeLog;
                            //add Mac address
                            newRow["MACaddress"] = r["macaddress"];
                            //add note
                            newRow["Note"] = r["Note"];
                        }
                    }
                }
            }
            //Add result to datatable
            dtDayInfo.Rows.Add(newRow);
        }//return table with data has insert
        return dtDayInfo;
    }
    /// <summary>
    /// Get information of user in period of time
    /// </summary>
    /// <param name="nameOfUser"></param>
    /// <param name="fr"></param>
    /// <param name="to"></param>
    /// <returns></returns>

    [WebMethod(Description = "Get user’s information detail in time (from time to other time):  date, status, time, MACaddress, Note")]
    public DataTable GetUserInfoDetailInTime(String strUserName, DateTime dtmStartDate, DateTime dtmEndDate)
    {
        //tmp datetime variable for date of start
        DateTime dtmDateStart = dtmStartDate;
        //tmp datetime variable for last date was chose 
        DateTime dtmDateEnd = dtmEndDate;
        //if user has inputted wrong
        if ((dtmDateEnd - dtmDateStart).TotalDays < 0)
        {
            //swap them
            dtmDateStart = dtmEndDate;
            dtmDateEnd = dtmStartDate;
        }
        //tmp table for hold data
        DataTable dtInfos = new DataTable();
        //set name to table
        dtInfos.TableName = "UserDetailTime";
        //add column to table
        dtInfos.Columns.Add("Date");
        //add colummn
        dtInfos.Columns.Add("Status");
        //add column
        dtInfos.Columns.Add("Time");
        //add column
        dtInfos.Columns.Add("MACAddress");
        //add column
        dtInfos.Columns.Add("Note");
        //sum of date from start date to last date  
        int intNumberOfDate = (int)((dtmDateEnd - dtmDateStart).TotalDays);
        //dealing witth each date
        for (int i = 0; i <= intNumberOfDate; i++)
        {
            //initializes a datatable that receive information 
            //from each date that returned from function 'GetUserInfoDetailInDay'
            //increase date by date to the end of array of date
            //it's reuse

            DataTable dtDetailInfo = GetUserInfoDetailInDay(strUserName, dtmDateStart.AddDays(i));
            //Creates a new System.Data.DataRow with the same schema as the table.
            DataRow drRowToInsert = dtInfos.NewRow();
            //assign column date
            drRowToInsert["Date"] = dtmDateStart.AddDays(i).ToShortDateString();
            //if DetailInfoTB is not null
            if (dtDetailInfo != null)
            {
                //if DetailInfoTB contains at least on row
                if (dtDetailInfo.Rows.Count > 0)
                {
                    //assign value for status comun
                    drRowToInsert["Status"] = dtDetailInfo.Rows[0]["status"];
                    //assign value for Time column
                    drRowToInsert["Time"] = dtDetailInfo.Rows[0]["time"];
                    //assign value for MAC
                    drRowToInsert["MACAddress"] = dtDetailInfo.Rows[0]["MACaddress"];
                    //assign value for Note
                    drRowToInsert["Note"] = dtDetailInfo.Rows[0]["Note"];
                }
            }
            //add rows has just edited
            dtInfos.Rows.Add(drRowToInsert);
        }
        //return table
        return dtInfos;

    }
    /// <summary>
    /// It's used by website to get an overview of user in a period of time
    /// </summary>
    /// <param name="nameOfUser"> UserName, such as ThiBT</param>
    /// <param name="from">Start Date wanna check</param>
    /// <param name="to">The date finished check</param>
    /// <returns></returns>
    [WebMethod(Description = "-	Get user info overview in time: return table with content number day present, number of day absence, and number of MAC")]
    public DataTable GetUserInfoOverviewInTime(String strUserName, DateTime dtmStartdDate, DateTime dtmEndDate)
    {
        //tmp  'from date'
        DateTime dtmDateStart = dtmStartdDate;
        //tmp 'to date'
        DateTime dtmDateEnd = dtmEndDate;
        //if 'to date' is date that's come before 'from date'
        if ((dtmEndDate - dtmStartdDate).TotalDays < 0)
        {
            //swap them
            dtmDateStart = dtmEndDate;
            dtmDateEnd = dtmStartdDate;
        }
        //Count the dates that user has checked attendance, default value is  0
        int intPresentDays = 0;
        //Count the dates that user hasnot checked attendance, default value is 0
        int intdAbsenceDays = 0;
        //Count MACs that user has used, default value is 0
        int intNumMac = 0;
        //tmp Table
        DataTable dtOverview = new DataTable();
        //set name for table
        dtOverview.TableName = "OverviewTime";
        //add colume to table
        dtOverview.Columns.Add("Username");
        //add column that show sum dates of present
        dtOverview.Columns.Add("Days present");
        //add column that show sum dates of absence
        dtOverview.Columns.Add("Days absence");
        //add column that show sum MACs had been user
        dtOverview.Columns.Add("Number of MAC");
        //Create a new row for save data
        DataRow row = dtOverview.NewRow();
        //Initializes table that hold values (or table) from function 'GetUserInfoDetailInTime'
        //It's reused
        DataTable dtDetailInfo = GetUserInfoDetailInTime(strUserName, dtmDateStart, dtmDateEnd);
        //first row is username
        row[0] = strUserName;
        //count number of date user wanna check
        int intNumDates = (int)(dtmDateEnd - dtmDateStart).TotalDays;
        //with each date, do
        for (int i = 0; i <= (intNumDates); i++)
        {
            //increase '1' to date, for browse all date
            //and assign it to temp date
            DateTime dtmDate = dtmDateStart.AddDays(i);
            //browse all row in table 'UserDetailInTime'
            for (int j = 0; j < dtDetailInfo.Rows.Count; j++)
            {
                //create a  temp variable type of Datetime
                DateTime dtmLogDate;
                //get time user checked attendence from colume 'time' in table 'UserDetailInTime' 
                //and assign it to variable 'logDay'
                if (DateTime.TryParse(dtDetailInfo.Rows[j][2].ToString(),out dtmLogDate))
                {
                    //check if day is equal to logday
                    //and if there's a value in Table's time column mean that 
                    //that day, user has checked attendance, otherwise absence.
                    if (dtmDate.DayOfYear == dtmLogDate.DayOfYear && dtmDate.Year == dtmLogDate.Year)
                    {
                        //increase daysPresent by 1
                        intPresentDays = intPresentDays + 1;
                    }
                }                
            }
        }
        //after count day present, absence days = sum of days - present days. 
        intdAbsenceDays = (intNumDates+1) - intPresentDays;
        //Use function 'GetAllMACaddressOfUserInTime' to return a table has 
        //each row contain diffenrent MAC addresses
        //mean that "one row, one MAC"
        intNumMac = GetAllMACaddressOfUserInTime(strUserName, dtmDateStart, dtmDateEnd).Count; ;
        //set value for each column
        row[1] = intPresentDays;
        row[2] = intdAbsenceDays;
        row[3] = intNumMac;
        //Add row to table
        dtOverview.Rows.Add(row);
        //return table contain desired text
        return dtOverview;

    }
    /// <summary>
    /// Return number of mac address in a period of time
    /// </summary>
    /// <param name="nameOfUser"></param>
    /// <param name="from"></param>
    /// <param name="to"></param>
    /// <returns></returns>
    [WebMethod(Description = "Get all MAC address of user in time (time to time): return table with columns: Username, sortNumber, MACAddress")]
    public List<String> GetAllMACaddressOfUserInTime(String strUserName, DateTime dtmStartdate, DateTime dtmEndDate)
    {
        //if inputs of user are not right, 
        if ((dtmEndDate - dtmStartdate).TotalDays < 0)
        {
            //tmp variable for swapping 
            DateTime dtmTempDate = new DateTime();
            //start swap
            dtmTempDate = dtmEndDate;
            dtmEndDate = dtmStartdate;
            dtmStartdate = dtmTempDate;
        }
        //Create a list to hold array of MAC address 
        List<String> mac = new List<string>();
        //use the function 'GetUserInfoDetailInTime' to get a table
        //This table look likes that:
        /*
         * 
         *  Date  Status  Time    MAC Address Note
         *
         */
        DataTable dtUserInfo = GetUserInfoDetailInTime(strUserName, dtmStartdate, dtmEndDate);
        //check if null
        if (dtUserInfo.Rows.Count > 0)
        {
            //browse all rows of table
            for (int i = 0; i < dtUserInfo.Rows.Count; i++)
            {
                //Checked MAC if exist in tmp List
                bool bIsExist = false;
                //tmp variable to hold each MAC in this table
                String strMac = dtUserInfo.Rows[i]["MACAddress"].ToString();
                //browse all MACs to check if equal
                for (int j = 0; j < mac.Count; j++)
                {
                    //if yes
                    if (strMac.Equals(mac[j].ToString()))
                    {
                        //mark as exist, and dont insert into temp List
                        bIsExist = true;
                        //dont keep check, break
                        break;
                    }
                }
                //MAC was not exist in temp List yet
                if (!bIsExist)
                {
                    //insert in to MAC List, 
                    mac.Insert(0, strMac);
                }
            }
        }
        //Nothing from Dataset then, return null
        else
        {
            return null;
        }
        //return MAC List
        return mac;
    }
    /// <summary>
    /// find out with users have the same mac address
    /// </summary>
    /// <param name="MAC">mac address</param>
    /// <param name="from"></param>
    /// <param name="to"></param>
    /// <returns></returns>
    [WebMethod(Description = "Get all User use  a MAC dress in time (time to time): return a table with columns: sortNumber, Username")]
    public List<string> GetAllUserOfMACaddressInTime(String strMAC, DateTime dtmFrom, DateTime dtmTo)
    {
        //if dates's not in right order
        if ((dtmTo - dtmFrom).TotalDays < 0)
        {
            //Start swap
            DateTime dtmTempDate = dtmFrom;
            dtmFrom = dtmTo;
            dtmTo = dtmTempDate;
        }
        //temp List of User
        List<String> lstUsers = new List<string>();
        //Create a datarow for hold Dataset DS
        //because Dataset just contains one table "PersonDailyLog" then -> table[0] 
        //then fitler it with MAC address
        //when done, it's a table with rows contains this MAC address value
        DataRow[] drMacs = serviceForUser.GetDataset().Tables[0].Select("MACAddress = '" + strMAC.Trim() + "'");
        //hold value to show that User already in List or not
        bool blIsExist = false;
        //browse all rows 
        foreach (DataRow r in drMacs)
        {
            //tmp variable for hold userID got from 
            long lUserIDLog = long.Parse(r[1].ToString().Trim());
            //Get username from userID
            String strUserLog = serviceForHainfo.GetUserAccount(lUserIDLog);
            //Browse all username in list to check if exist
            for (int i = 0; i < lstUsers.Count; i++)
            {
                //if already exist
                if (strUserLog.Trim().ToLower().Equals(lstUsers[i].ToString().Trim().ToLower()))
                {
                    //Mark as exist
                    blIsExist = true;
                    //stop browsing and break
                    break;
                }

            }
            //if username's not in list yet
            if (!blIsExist)
            {
                //add username to list
                lstUsers.Add(strUserLog);  
            }
            //assign again is exist = false for new browse
            blIsExist = false;
        }
        //return list of users that used a same MAC
        return lstUsers;
    }

    /// <summary>
    /// 
    /// </summary>
    /// <param name="dtmFrom"></param>
    /// <param name="dtmTo"></param>
    /// <returns>a table with columns: Username, number day present, number day absence, and number of MAC</returns>
    [WebMethod(Description = "Get all information of all users in period of time")]
    public DataTable GetAllUserInfoOverviewInTime(DateTime dtmFrom, DateTime dtmTo)
    {
        //if dates's not in right order
        if ((dtmTo - dtmFrom).TotalDays < 0)
        {
            //Start swap
            DateTime dtmTempDate = dtmFrom;
            dtmFrom = dtmTo;
            dtmTo = dtmTempDate;
        }
        //create datatable for hold needed information
        DataTable dtOverView = new DataTable();
        //Add correspond column
        dtOverView.Columns.Add("Full name");
        dtOverView.Columns.Add("Username");
        dtOverView.Columns.Add("FU");
        dtOverView.Columns.Add("Days present");
        dtOverView.Columns.Add("Days absence");
        dtOverView.Columns.Add("Number of MAC");
        dtOverView.TableName = "allUserOverviewTB";
        //Create a table with hold all user at RTD 
        DataTable dtAllUsers = serviceForHainfo.GetUsersAtRtd();
        //browse all rows
        for (int i = 0; i < dtAllUsers.Rows.Count; i++)
        {
            //add a new row
            DataRow rNewRow = dtOverView.NewRow();
            //create a tmp table for hold values from functon 'GetUserInfoOverviewInTime'
            //functon 'GetUserInfoOverviewInTime' return
            //Username  NumPresent   NumAbsence NumMAC
            DataTable eachUser = GetUserInfoOverviewInTime(dtAllUsers.Rows[i][2].ToString(), dtmFrom, dtmTo);
            //assign property of this new row with value from allUser table            
            rNewRow["Full name"] = dtAllUsers.Rows[i][1];
            rNewRow["FU"] = dtAllUsers.Rows[i][3];
            rNewRow["Username"] = eachUser.Rows[0][0];
            rNewRow["Days present"] = eachUser.Rows[0][1];
            rNewRow["Days absence"] = eachUser.Rows[0][2];
            rNewRow["Number of MAC"] = eachUser.Rows[0][3];
            //add row to database
            dtOverView.Rows.Add(rNewRow);
        }
        //return table
        return dtOverView;

    }
    /// <summary>
    /// return table with columns: Name, Username, Status, time"
    /// </summary>
    /// <param name="day"></param>
    /// <returns></returns>
    [WebMethod(Description = "Get information of all users in a date. ")]
    public DataTable UsersInfoInDay(DateTime dtmDay)
    {
        //create a datatable for hold data
        DataTable dtAllInformation = new DataTable();
        //Add column to database
        dtAllInformation.TableName = "GetUserInfoDetailInDay";
        dtAllInformation.Columns.Add("Full name");
        dtAllInformation.Columns.Add("Username");
        dtAllInformation.Columns.Add("FU");
        dtAllInformation.Columns.Add("status");
        dtAllInformation.Columns.Add("time");
        dtAllInformation.Columns.Add("MACaddress");
        dtAllInformation.Columns.Add("Note");
        //create a temp datatable for hold data from function 'GetAllUsersAtRTD'
        //function 'GetAllUsersAtRTD' return a table with 
        // UserID FullName UserName FU      
        DataTable dtAllUsers = GetAllUsersAtRtd();
        //Browse all rows of above datatable
        for (int i = 0; i < dtAllUsers.Rows.Count; i++)
        {
            //do
            try
            {
                //Create a temp variable and assign to it with value from Row
                String strUser = dtAllUsers.Rows[i][2].ToString();
                //create a temp datatable to hold value from function 'GetUserInfoDetailInDay'
                //function 'GetUserInfoDetailInDay' return a table with
                //Username | Status | time | MACaddress | Note
                DataTable dtAllUsersInfo = GetUserInfoDetailInDay(strUser, dtmDay);
                //create a new row to table 'Tb', for using after
                DataRow drNewRow = dtAllInformation.NewRow();
                //in new row, assign value to each column 
                drNewRow["Full name"] = dtAllUsers.Rows[i][1].ToString();
                drNewRow["Username"] = dtAllUsersInfo.Rows[0]["Username"];
                drNewRow["FU"] = dtAllUsers.Rows[i][3];
                drNewRow["status"] = dtAllUsersInfo.Rows[0]["status"];
                drNewRow["time"] = dtAllUsersInfo.Rows[0]["time"];
                drNewRow["MACaddress"] = dtAllUsersInfo.Rows[0]["MACaddress"];
                drNewRow["Note"] = dtAllUsersInfo.Rows[0]["Note"];
                //Do task
                dtAllInformation.Rows.Add(drNewRow);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
        //return table 
        return dtAllInformation;
    }

    /// <summary>
    /// Get all users info in week
    /// </summary>
    /// <returns></returns>
    [WebMethod(Description = "Get all users info in this Week: Username; status of days")]
    public DataTable UsersInfoInWeek()
    {
        //Gets the day of the week represented by this instance.
        int intDayOfWeek = (int)DateTime.Now.DayOfWeek;
        //the date begin current week
        DateTime dtmBeginDateOfWeek = DateTime.Now.AddDays(-intDayOfWeek);
        //the date at the end of current week
        DateTime dtmEndDateOfWeek = dtmBeginDateOfWeek.AddDays(6);
        //Create a temp table
        DataTable dtAllInfoInWeek = new DataTable();
        //Add name for table
        dtAllInfoInWeek.TableName = "AllUsersInfoInThisWeek";
        // add Columns Name
        dtAllInfoInWeek.Columns.Add("Full name");
        dtAllInfoInWeek.Columns.Add("Username");
        dtAllInfoInWeek.Columns.Add(dtmBeginDateOfWeek.DayOfWeek.ToString());
        dtAllInfoInWeek.Columns.Add(dtmBeginDateOfWeek.AddDays(1).DayOfWeek.ToString());
        dtAllInfoInWeek.Columns.Add(dtmBeginDateOfWeek.AddDays(2).DayOfWeek.ToString());
        dtAllInfoInWeek.Columns.Add(dtmBeginDateOfWeek.AddDays(3).DayOfWeek.ToString());
        dtAllInfoInWeek.Columns.Add(dtmBeginDateOfWeek.AddDays(4).DayOfWeek.ToString());
        dtAllInfoInWeek.Columns.Add(dtmBeginDateOfWeek.AddDays(5).DayOfWeek.ToString());
        dtAllInfoInWeek.Columns.Add(dtmBeginDateOfWeek.AddDays(6).DayOfWeek.ToString());
        //create a table for hold information from 'GetUsersAtRTD'
        //function 'GetUsersAtRTD' return a table with columns:
        //// UserID | FullName | UserName | FU 
        DataTable dtUserList = serviceForHainfo.GetUsersAtRtd();
        //clear table
        dtAllInfoInWeek.Rows.Clear();
        //browse all user
        for (int i = 0; i < dtUserList.Rows.Count; i++)
        {
            //Create a temp datarow, it's on behalf of each row of table 'AllUsersInfoInThisWeek'
            DataRow drNewRow = dtAllInfoInWeek.NewRow();
            //Add fullname
            drNewRow[0] = dtUserList.Rows[i][1];
            //add username
            drNewRow[1] = dtUserList.Rows[i][2];
            //create a temp table 'dt' and give it a parameter (username)
            //then take another values - status of Monday-> Sunday 
            DataTable dtUserWeekInfo = GetUserInfoInThisWeek(dtUserList.Rows[i][2].ToString());
            //if dt has values
            if (dtUserWeekInfo!=null)
            {
                //assign for sunday
                drNewRow[2] = dtUserWeekInfo.Rows[0][1];
                //assign for monday
                drNewRow[3] = dtUserWeekInfo.Rows[0][2];
                //assign for tuesday
                drNewRow[4] = dtUserWeekInfo.Rows[0][3];
                //assign for wednesday
                drNewRow[5] = dtUserWeekInfo.Rows[0][4];
                //assign for thusday
                drNewRow[6] = dtUserWeekInfo.Rows[0][5];
                //assign for friday
                drNewRow[7] = dtUserWeekInfo.Rows[0][6];
                //assign for saturday
                drNewRow[8] = dtUserWeekInfo.Rows[0][7];
                //add row to table
                dtAllInfoInWeek.Rows.Add(drNewRow);
            }
            else
            {
                //Returns a System.String that represents the current System.Object.
                dtUserList.Rows[i][2].ToString();
            }
        }
        //return table
        return dtAllInfoInWeek;

    }


    //Return a table look likes this:
    //Full name	     Username	FU	    10/17/2011	 10/18/2011	 10/19/2011	     10/20/2011
	//Bùi Tường Thi	  ThiBT	   FU.K4c	  8:36 AM	   8:49 AM	   8:33 AM	       8:16 AM
	/// <summary>
	/// 
	/// </summary>
	/// <param name="dtmFrom"></param>
	/// <param name="dtmTo"></param>
	/// <returns></returns>
    [WebMethod(Description = "")]
    public DataTable GetAllUsersInfoInTime(DateTime dtmStartdate, DateTime dtmEndDate)
    {
        //if date's not in an right order
        if((dtmEndDate-dtmStartdate).TotalDays<0)
        {
            //start swap
            DateTime dtmTempDate = dtmStartdate;
            dtmStartdate = dtmEndDate;
            dtmEndDate = dtmTempDate;
        }
        //create a temp table that hold a view 
        // UserID | FullName | UserName | FU  
        DataTable dtAllUsers = GetAllUsersAtRtd().Copy();
        //count the number of dates
        int intNumDates = (int)(dtmEndDate-dtmStartdate).TotalDays;
        //create a temp table to return when finished
        DataTable tbAllUsersInfo = new DataTable();
        //Assign name for table
        tbAllUsersInfo.TableName = "GetAllUsersInfoInTime";
        //add column to table
        tbAllUsersInfo.Columns.Add("Full name");
        //add column to table
        tbAllUsersInfo.Columns.Add("Username");
        //add column to table
        tbAllUsersInfo.Columns.Add("FU");
        //for each day
        for (int i = 0; i <= intNumDates; i++)
        {
            //if current dates is not Saturday and Sunday
            if ((int)dtmStartdate.AddDays(i).DayOfWeek != 0 && (int)dtmStartdate.AddDays(i).DayOfWeek != 6)
            {
                //Add current date (in short format, such as '10/17/2011') to table 
                tbAllUsersInfo.Columns.Add(dtmStartdate.AddDays(i).ToShortDateString());
            }

        }
        //with all users in column
        for (int i = 0; i < dtAllUsers.Rows.Count; i++)
        {
            //create a new row 
            DataRow drNewRow = tbAllUsersInfo.NewRow();
            //add fullname to first column of row
            drNewRow[0] = dtAllUsers.Rows[i][1].ToString();
            //add username to second column of row
            drNewRow[1] = dtAllUsers.Rows[i][2].ToString();
            //add batch to third column of row
            drNewRow[2] = dtAllUsers.Rows[i][3];
            //date number, posroll = 3 (4th column), show status of user at the first date. 
            //
            int intPostRoll = 3;
            //with all days in table
            for (int j = 0; j <= intNumDates; j++)
            {
                //when date not in Sunday or Saturday
                if ((int)dtmStartdate.AddDays(j).DayOfWeek != 0 && (int)dtmStartdate.AddDays(j).DayOfWeek != 6)
                {
                    //create a temp datatable with parameters:  username + date
                    //table return looks like this:
                    //Username	| status | time	| MACaddress | Note
                    DataTable dtDateInfoUser = GetUserInfoDetailInDay(dtAllUsers.Rows[i][2].ToString(), dtmStartdate.AddDays(j));
                    //if time is null
                    if ((dtDateInfoUser.Rows[0]["time"]).ToString().Trim().Equals(""))
                    {
                        //mean that date, there no checking by user -> absence
                        drNewRow[intPostRoll] = "Absence";
                        //increase by 1 to check the next date
                        intPostRoll = intPostRoll + 1;
                    }
                    //User has checked that date
                    else
                    {
                        //Get date and parsing it
                        DateTime dtmTempDate = DateTime.Parse((dtDateInfoUser.Rows[0]["time"]).ToString());
                        //in format looks like this:  8:36 AM
                        drNewRow[intPostRoll] = dtmTempDate.ToShortTimeString();
                        //increase by 1 to check the next date
                        intPostRoll = intPostRoll + 1;
                    }
                }

            }
            //add row to table
            tbAllUsersInfo.Rows.Add(drNewRow);
        }
        //return table
        return tbAllUsersInfo;
    }
    /// <summary>
    /// Modify information of user
    /// </summary>
    /// <param name="userUpdate"></param>
    /// <param name="day"></param>
    /// <param name="MacAdd"></param>
    /// <param name="note"></param>
    /// <param name="updatetor"></param>
    /// <returns></returns>
    
    [WebMethod(Description = "Modify a User infomation in specific day")]
    public bool UpdateUserInfoInDay(String strUser, DateTime dtmDate, String strMac, String strNote, String strModifiedBy)
    {
        //Get ID of user with username
        long logID = serviceForHainfo.GetUserId(strUser);
        //if username supplied has a correspond ID
        if (logID > 0)
        {
            //Return trueUpdate information with that ID
            return serviceForUser.UpdateUserInfoInDay(logID, dtmDate, strMac, strNote, strModifiedBy);
        }
        //else show update fail and return false
        return false;
    }

    //Return a table that looks like this:
    //Username	Sunday	    Monday	                Tuesday	            Wednesday......	
    //thibt	    Absence	10/24/2011 8:34:16 AM	10/25/2011 8:39:20 AM	10/26/2011 8:32:05 AM	
    /// <summary>
    /// get information of user at this week
    /// </summary>
    /// <param name="userCheck"></param>
    /// <returns></returns>
    [WebMethod(Description = "Get infomation of User at this week")]
    public DataTable GetUserInfoInThisWeek(String strUserName)
    {
        //get ID of username
        long logID = serviceForHainfo.GetUserId(strUserName);
        //Gets the day of the week
        int intDateOfWeek = (int)DateTime.Now.DayOfWeek;
        //First date of week
        DateTime dtmBeginDate = DateTime.Now.AddDays(-intDateOfWeek);
        //End date of week
        DateTime dtmEndDate = dtmBeginDate.AddDays(6);
        //temp table to hold values
        DataTable dtWeekInfoUser = new DataTable();
        //Add table name
        dtWeekInfoUser.TableName = "UserInfoInThisWeekTB";
        //Add Username Column 
        dtWeekInfoUser.Columns.Add("Username");
        //Add All Datecolummn to table 
        dtWeekInfoUser.Columns.Add(dtmBeginDate.DayOfWeek.ToString());
        dtWeekInfoUser.Columns.Add(dtmBeginDate.AddDays(1).DayOfWeek.ToString());
        dtWeekInfoUser.Columns.Add(dtmBeginDate.AddDays(2).DayOfWeek.ToString());
        dtWeekInfoUser.Columns.Add(dtmBeginDate.AddDays(3).DayOfWeek.ToString());
        dtWeekInfoUser.Columns.Add(dtmBeginDate.AddDays(4).DayOfWeek.ToString());
        dtWeekInfoUser.Columns.Add(dtmBeginDate.AddDays(5).DayOfWeek.ToString());
        dtWeekInfoUser.Columns.Add(dtmBeginDate.AddDays(6).DayOfWeek.ToString());
        //If exiest a userID with username parameter 
        if (logID > 0)
        {
            //temp new row for hold data
            DataRow drNewRow = dtWeekInfoUser.NewRow();
            //Add username to column Username in current row
            drNewRow["Username"] = strUserName;
            //browse all dates in this week
            for (int i = 0; i <= intDateOfWeek; i++)
            {
                //create temp for get data from function 'GetUserInfoDetailInDay'
                //this 'GetUserInfoDetailInDay' return table look likes
                //Username	status	  time                 	MACaddress	   Note
                // thibt	Present	10/28/2011 7:59:13 AM	001EECBEB9D9	 
                DataTable dtDateInfoUser = GetUserInfoDetailInDay(strUserName, dtmBeginDate.AddDays(i));
                //if that date, user've not check attendance
                if (dtDateInfoUser.Rows[0]["time"].ToString().Trim().Equals(""))
                {
                    //Add status of this date get from function 'UserInfoDetailInDay'
                    drNewRow[(i + 1)] = dtDateInfoUser.Rows[0]["status"];
                }
                else
                {
                    //Add time log
                    drNewRow[(i + 1)] = dtDateInfoUser.Rows[0]["time"];
                }
            }
            //add new row to that table
            dtWeekInfoUser.Rows.Add(drNewRow);
        }
        //return table
        return dtWeekInfoUser;
    }

    








    //***************************************************************************************
    /*
     *All Function Name in this page will be setted in the User's view of point (Client) 
     *Now I will set above functions to others names for more properly.   
     */
    //=====================GETCURRENTMACADDRESS====================
    //Return the Mac address of local machine
    //It's now for test only
    /// <summary>
    /// set current mac address
    /// </summary>
    /// <returns></returns>
    public String SetCurrentMACAddress()
    {
        // Browse all network interface to return right mac address

        //return Mac address when connected by Wifi
        foreach (NetworkInterface ni in NetworkInterface.GetAllNetworkInterfaces())
        {   //Gets the current operational state of the network connection.
            //and check the network interface is up; it can transmit data packets.
            if (ni.OperationalStatus == OperationalStatus.Up &&
                //and check if the network interface is unable to transmit data packets because of a missing
                //component, typically a hardware component.
                    ni.OperationalStatus != OperationalStatus.NotPresent &&
                //Check if the network interface uses a tunnel connection.
                //if yes, we can't get Mac address
                        ni.NetworkInterfaceType != NetworkInterfaceType.Tunnel &&
                //Check if the network interfacs is a loopback adapter.
                //if yes, it's just for testing; no traffic is sent.
                            ni.NetworkInterfaceType != NetworkInterfaceType.Loopback &&
                //The network interface uses a wireless LAN connection (IEEE 802.11 standard).
                                    ni.NetworkInterfaceType == NetworkInterfaceType.Wireless80211)
            {
                //return mac address
                return ni.GetPhysicalAddress().ToString();
            }
            //return mac address when connected by Ethernet
            if (ni.NetworkInterfaceType == NetworkInterfaceType.Ethernet &&
                //Gets the current operational state of the network connection.
                //and check the network interface is up; it can transmit data packets.
                    ni.OperationalStatus == OperationalStatus.Up)
            {
                //return mac address
                return ni.GetPhysicalAddress().ToString();
            }
        }
        //if there's no mac address, return NULL
        return null;
    }
    /// <summary>
    /// get information of user
    /// </summary>
    /// <param name="userName"></param>
    /// <param name="MAC"></param>
    /// <param name="Security">84ac41d7c57ea25694b0cb7899a104f5 is secret key</param>
    /// <returns>0 if user checked, 1 if user check successful, -1 if user check error</returns>
    [WebMethod(Description = "Get information of user to check log")]
    public int CheckAttendance(String strUserName, string strMAC, string strSecurity)
    {
        if (strSecurity.Equals("84ac41d7c57ea25694b0cb7899a104f5"))
        {
            try
            {
                //assign ID with correspond username
                long ID = serviceForHainfo.GetUserId(strUserName);
                //ID > 0, mean that survive user in Database
                if (ID > 0)
                {
                    //initializes a user with that ID and username
                    user = new User(ID, strMAC);
                    //initializes a userservice with above user to carries out tasks
                    serviceForUser = new UserService(user);
                    //Check if user was checked at current day
                    //If user has been checked
                    if (serviceForUser.IsUserChecked())
                    {
                        //return  0 to client for making a balloon show that user's checked
                        return 0;

                    }
                    //if user has been not checked
                    else
                    {
                        //if insert into database successful
                        if (serviceForUser.InsertNewRow())
                        {
                            //update database
                            serviceForUser.UpdateDataBase();
                            //return 1 show that user has just checked attendence successful 
                            return 1;

                        }
                        //else if user has not checked current day, but can't be marked as checked
                        else
                        {
                            return -1;
                        }
                    }
                }
                //If ID < 0, show that in database has no that name
                else
                {
                    return 2;
                }
            }
            catch
            {
                //can't insert data into database
                return -1;

            }
        }
        else
            return -1;
    }

    public string CheckCheck(String strUserName, string strMAC, string strSecurity)
    {
        if (strSecurity.Equals("84ac41d7c57ea25694b0cb7899a104f5"))
        {
            try
            {
                //assign ID with correspond username
                long ID = serviceForHainfo.GetUserId(strUserName);
                //ID > 0, mean that survive user in Database
                if (ID > 0)
                {
                    //initializes a user with that ID and username
                    user = new User(ID, strMAC);
                    //initializes a userservice with above user to carries out tasks
                    serviceForUser = new UserService(user);
                    //Check if user was checked at current day
                    //If user has been checked
                    if (serviceForUser.IsUserChecked())
                    {
                        //return  0 to client for making a balloon show that user's checked
                        return "0";

                    }
                    //if user has been not checked
                    else
                    {
                        //if insert into database successful
                        try
                        {
                            if (serviceForUser.InsertNewRow())
                            {
                                //update database
                                serviceForUser.UpdateDataBase();
                                //return 1 show that user has just checked attendence successful 
                                return "1";

                            }
                            //else if user has not checked current day, but can't be marked as checked
                            else
                            {
                                return "-1";
                            }
                        }
                        catch (Exception ex)
                        {

                            return ex.Message;
                        }


                    }
                }
                //If ID < 0, show that in database has no that name
                else
                {
                    return "2";
                }
            }
            catch
            {
                //can't insert data into database
                return "-1";

            }
        }
        else
            return "-1";
    }


    //=====================GETALLUSERSATRTD===================================
    /// <summary>
    /// get all user at time
    /// </summary>
    /// <returns></returns>
    [WebMethod(Description = "Get all user at this time(ID, name, Username, batch)")]
    public DataTable GetAllUsersAtThisTime()
    {
        //initializes a datatable to hold returned table
        DataTable DT = new DataTable();
        DT = serviceForHainfo.GetUsersAtRtd();
        //Set table name
        DT.TableName = "USeratRTD";
        //return data table
        return DT;
    }



    //============GETUSERINFODETAILINDAY================================================
    /*
     * input: User account and the specific day
     * return: Atable has 1 row content:Useraccout, Status, Timelog, MACAddress, Note
     * Require database has tabble Person and PersonDailyLog Inner join on Person.ID
     * */
    /// <summary>
    /// get information of user in exactly time
    /// </summary>
    /// <param name="nameOfUser"></param>
    /// <param name="day"></param>
    /// <returns></returns>
    [WebMethod(Description = "Get detail information of user in a specific day(username, status, time, MAC address, Note)")]
    public DataTable DetailInformaUserInDay(String strNameOfUser, DateTime dtmDay)
    {
        //initializes a datatable
        DataTable tb = new DataTable();
        //set name for table
        tb.TableName = "GetUserInfoDetailInDay";
        /*
         *Add Columeto table, it contains information of user in a date
         */
        tb.Columns.Add("Username");
        tb.Columns.Add("status");
        tb.Columns.Add("time");
        tb.Columns.Add("MACaddress");
        tb.Columns.Add("Note");
        //Check if username available
        long id = serviceForHainfo.GetUserId(strNameOfUser);
        //If yes
        if (id > 0)
        {
            //Add new row to table with correspond properties column
            DataRow newrow = tb.NewRow();
            //add name column
            newrow["Username"] = strNameOfUser;
            //add default status
            newrow["status"] = "Absence";
            //add time, default is nothing 
            newrow["time"] = "";
            //add MAC address,default is nothing
            newrow["MACaddress"] = "";
            //add note, default is nothing
            newrow["note"] = "";
            //Get data from Dataset and assign it to rows (with personID-fitler)
            DataRow[] rows = serviceForUser.GetDataset().Tables[0].Select("personid = '" + id + "'");
            //if there's items
            if (rows.Length > 0)
            {
                //browse all rows, with each item, do
                foreach (DataRow r in rows)
                {
                    //initializes a datetime object
                    DateTime timelog = new DateTime();
                    //try to convert a string to datetime type
                    //convert timelog in row into variable named timelog
                    //return success or fail
                    bool tryparse = DateTime.TryParse(r["timelog"].ToString(), out timelog);
                    //if success
                    if (tryparse)
                    {
                        //it's that day
                        if (timelog.DayOfYear == dtmDay.DayOfYear && timelog.Year == dtmDay.Year)
                        {
                            //add Present to status
                            newrow["status"] = "Present";
                            //add timelog to time
                            newrow["time"] = timelog;
                            //add Mac address
                            newrow["MACaddress"] = r["macaddress"];
                            //add note
                            newrow["Note"] = r["Note"];
                        }
                    }
                }
            }
            //Add result to datatable
            tb.Rows.Add(newrow);
        }//return table with data has insert
        return tb;
    }

    /// <summary>
    /// get detail information of a user in period of time
    /// </summary>
    /// <param name="nameOfUser"></param>
    /// <param name="fr"></param>
    /// <param name="to"></param>
    /// <returns></returns>
    [WebMethod(Description = "Get detail information of a User in period of time):  date, status, time, MACaddress, Note")]
    public DataTable DetailInfoUserInPeriodTime(String strNameOfUser, DateTime dtmFrom, DateTime to)
    {
        //tmp datetime variable for date of start
        DateTime fromDay = dtmFrom;
        //tmp datetime variable for last date was chose 
        DateTime toDay = to;
        //if user has inputted wrong
        if ((toDay - fromDay).TotalDays < 0)
        {
            //swap them
            fromDay = to;
            toDay = dtmFrom;
        }
        //tmp table for hold data
        DataTable tb = new DataTable();
        //set name to table
        tb.TableName = "UserDetailTime";
        //add column to table
        tb.Columns.Add("Date");
        //add colummn
        tb.Columns.Add("Status");
        //add column
        tb.Columns.Add("Time");
        //add column
        tb.Columns.Add("MACAddress");
        //add column
        tb.Columns.Add("Note");
        //sum of date from start date to last date  
        int numberDay = (int)((toDay - fromDay).TotalDays);
        //dealing witth each date
        for (int i = 0; i <= numberDay; i++)
        {
            //initializes a datatable that receive information 
            //from each date that returned from function 'GetUserInfoDetailInDay'
            //increase date by date to the end of array of date
            //it's reuse
            DataTable DetailInfoTB = GetUserInfoDetailInDay(strNameOfUser, fromDay.AddDays(i));
            //Creates a new System.Data.DataRow with the same schema as the table.
            DataRow r = tb.NewRow();
            //assign column date
            r["Date"] = fromDay.AddDays(i).ToShortDateString();
            //if DetailInfoTB is not null
            if (DetailInfoTB != null)
            {
                //if DetailInfoTB contains at least on row
                if (DetailInfoTB.Rows.Count > 0)
                {
                    //assign value for status comun
                    r["Status"] = DetailInfoTB.Rows[0]["status"];
                    //assign value for Time column
                    r["Time"] = DetailInfoTB.Rows[0]["time"];
                    //assign value for MAC
                    r["MACAddress"] = DetailInfoTB.Rows[0]["MACaddress"];
                    //assign value for Note
                    r["Note"] = DetailInfoTB.Rows[0]["Note"];
                }
            }
            //add rows has just edited
            tb.Rows.Add(r);
        }
        //return table
        return tb;

    }

    //==================================GETUSERINFOOVERVIEWINTIME==========================
    /// <summary>
    /// It's used by website
    /// </summary>
    /// <param name="nameOfUser"></param>
    /// <param name="from"></param>
    /// <param name="to"></param>
    /// <returns></returns>
    [WebMethod(Description = "Get user info overview in time: return table with content number day present, number of day absence, and number of MAC")]
    public DataTable InfoUserInPeriodTime(String strNameOfUser, DateTime strFrom, DateTime strTo)
    {
        //tmp  'from date'
        DateTime fromDay = strFrom;
        //tmp 'to date'
        DateTime toDay = strTo;
        //if 'to date' is date that's come before 'from date'
        if ((strTo - strFrom).TotalDays < 0)
        {
            //swap them
            fromDay = strTo;
            toDay = strFrom;
        }
        //Count the dates that user has checked attendance, default value is  0
        int daysPresent = 0;
        //Count the dates that user hasnot checked attendance, default value is 0
        int daysAbsence = 0;
        //Count MACs that user has used, default value is 0
        int numberMAC = 0;
        //tmp Table
        DataTable overviewTB = new DataTable();
        //set name for table
        overviewTB.TableName = "OverviewTime";
        //add colume to table
        overviewTB.Columns.Add("Username");
        //add column that show sum dates of present
        overviewTB.Columns.Add("Days present");
        //add column that show sum dates of absence
        overviewTB.Columns.Add("Days absence");
        //add column that show sum MACs had been user
        overviewTB.Columns.Add("Number of MAC");
        //Create a new row for save data
        DataRow row = overviewTB.NewRow();
        //Initializes table that hold values (or table) from function 'GetUserInfoDetailInTime'
        //It's reused
        DataTable UserDetailInTime = GetUserInfoDetailInTime(strNameOfUser, fromDay, toDay);
        //first row is username
        row[0] = strNameOfUser;
        //count number of date user wanna check
        int numberDay = (int)(toDay - fromDay).TotalDays;
        //with each date, do
        for (int i = 0; i <= (numberDay); i++)
        {
            //increase '1' to date, for browse all date
            //and assign it to temp date
            DateTime day = fromDay.AddDays(i);
            //browse all row in table 'UserDetailInTime'
            for (int j = 0; j < UserDetailInTime.Rows.Count; j++)
            {
                //create a  temp variable type of Datetime
                DateTime logDay;
                //get time user checked attendence from colume 'time' in table 'UserDetailInTime' 
                //and assign it to variable 'logDay'
                if (DateTime.TryParse(UserDetailInTime.Rows[j][2].ToString(), out logDay))
                {
                    //check if day is equal to logday
                    //and if there's a value in Table's time column mean that 
                    //that day, user has checked attendance, otherwise absence.
                    if (day.DayOfYear == logDay.DayOfYear && day.Year == logDay.Year)
                    {
                        //increase daysPresent by 1
                        daysPresent = daysPresent + 1;
                    }
                }
            }
        }
        //after count day present, absence days = sum of days - present days. 
        daysAbsence = (numberDay + 1) - daysPresent;
        //Use function 'GetAllMACaddressOfUserInTime' to return a table has 
        //each row contain diffenrent MAC addresses
        //mean that "one row, one MAC"
        numberMAC = GetAllMACaddressOfUserInTime(strNameOfUser, fromDay, toDay).Count;
        //set value for each column
        row[1] = daysPresent;
        row[2] = daysAbsence;
        row[3] = numberMAC;
        //Add row to table
        overviewTB.Rows.Add(row);
        //return table contain desired text
        return overviewTB;

    }

    /// <summary>
    /// Get all MAC address of user in period of time
    /// </summary>
    /// <param name="nameOfUser"></param>
    /// <param name="from"></param>
    /// <param name="to"></param>
    /// <returns></returns>
    [WebMethod(Description = "Get all MAC address of user in period of time: return table with columns: Username, sortNumber, MACAddress")]
    //Return numbers of MAC address of user in period of time 
    public List<String> GetAllMACaddressOfUserInPeriodOfTime(String nameOfUser, DateTime from, DateTime to)
    {
        //if inputs of user are not right, 
        if ((to - from).TotalDays < 0)
        {
            //tmp variable for swapping 
            DateTime daytmp = new DateTime();
            //start swap
            daytmp = to;
            to = from;
            from = daytmp;
        }
        //Create a list to hold array of MAC address 
        List<String> MAC = new List<string>();
        //use the function 'GetUserInfoDetailInTime' to get a table
        //This table look likes that:
        /*
         * 
         *  Date  Status  Time    MAC Address Note
         *
         */
        DataTable UserInfoTB = GetUserInfoDetailInTime(nameOfUser, from, to);
        //check if null
        if (UserInfoTB.Rows.Count > 0)
        {
            //browse all rows of table
            for (int i = 0; i < UserInfoTB.Rows.Count; i++)
            {
                //Checked MAC if exist in tmp List
                bool isExist = false;
                //tmp variable to hold each MAC in this table
                String MACOfDay = UserInfoTB.Rows[i]["MACAddress"].ToString();
                //browse all MACs to check if equal
                for (int j = 0; j < MAC.Count; j++)
                {
                    //if yes
                    if (MACOfDay.Equals(MAC[j].ToString()))
                    {
                        //mark as exist, and dont insert into temp List
                        isExist = true;
                        //dont keep check, break
                        break;
                    }
                }
                //MAC was not exist in temp List yet
                if (!isExist)
                {
                    //insert in to MAC List, 
                    MAC.Insert(0, MACOfDay);
                }
            }
        }
        //Nothing from Dataset then, return null
        else
        {
            return null;
        }
        //return MAC List
        return MAC;
    }

    /// <summary>
    /// Get user have the same mac address
    /// </summary>
    /// <param name="MAC"></param>
    /// <param name="from"></param>
    /// <param name="to"></param>
    /// <returns></returns>
    [WebMethod(Description = "Get all User use  a same MAC address in time (time to time): return a table with columns: sortNumber, Username")]
    public List<string> GetAllUsersHaveASameMacAddressInPeriodOfTime(String MAC, DateTime from, DateTime to)
    {
        //if dates's not in right order
        if ((to - from).TotalDays < 0)
        {
            //Start swap
            DateTime d = from;
            from = to;
            to = d;
        }
        //temp List of User
        List<String> userList = new List<string>();
        //Create a datarow for hold Dataset DS
        //because Dataset just contains one table "PersonDailyLog" then -> table[0] 
        //then fitler it with MAC address
        //when done, it's a table with rows contains this MAC address value
        DataRow[] rows = serviceForUser.GetDataset().Tables[0].Select("MACAddress = '" + MAC.Trim() + "'");
        //hold value to show that User already in List or not
        bool isExist = false;
        //browse all rows 
        foreach (DataRow r in rows)
        {
            //tmp variable for hold userID got from 
            long userIDLog = long.Parse(r[1].ToString().Trim());
            //Get username from userID
            String UserLog = serviceForHainfo.GetUserAccount(userIDLog);
            //Browse all username in list to check if exist
            for (int i = 0; i < userList.Count; i++)
            {
                //if already exist
                if (UserLog.Trim().ToLower().Equals(userList[i].ToString().Trim().ToLower()))
                {
                    //Mark as exist
                    isExist = true;
                    //stop browsing and break
                    break;
                }

            }
            //if username's not in list yet
            if (!isExist)
            {
                //add username to list
                userList.Add(UserLog);
            }
            //assign again is exist = false for new browse
            isExist = false;
        }
        //return list of users that used a same MAC
        return userList;
    }
    /// <summary>
    /// return a table with columns: Username, number day present, number day absence, and number of MAC
    /// </summary>
    /// <param name="from"></param>
    /// <param name="to"></param>
    /// <returns></returns>
    [WebMethod(Description = "Get Overview information of all users in period of time")]
    public DataTable GetOverviewInformationOfAllUsersInPeriodOfTime(DateTime from, DateTime to)
    {
        //if dates's not in right order
        if ((to - from).TotalDays < 0)
        {
            //Start swap
            DateTime d = from;
            from = to;
            to = d;
        }
        //create datatable for hold needed information
        DataTable allUserOverviewTB = new DataTable();
        //Add correspond column
        allUserOverviewTB.Columns.Add("Full name");
        allUserOverviewTB.Columns.Add("Username");
        allUserOverviewTB.Columns.Add("FU");
        allUserOverviewTB.Columns.Add("Days present");
        allUserOverviewTB.Columns.Add("Days absence");
        allUserOverviewTB.Columns.Add("Number of MAC");
        allUserOverviewTB.TableName = "allUserOverviewTB";
        //Create a table with hold all user at RTD 
        DataTable allUser = serviceForHainfo.GetUsersAtRtd();
        //browse all rows
        for (int i = 0; i < allUser.Rows.Count; i++)
        {
            //add a new row
            DataRow row = allUserOverviewTB.NewRow();
            //create a tmp table for hold values from functon 'GetUserInfoOverviewInTime'
            //functon 'GetUserInfoOverviewInTime' return
            //Username  NumPresent   NumAbsence NumMAC
            DataTable eachUser = GetUserInfoOverviewInTime(allUser.Rows[i][2].ToString(), from, to);
            //assign property of this new row with value from allUser table            
            row["Full name"] = allUser.Rows[i][1];
            row["FU"] = allUser.Rows[i][3];
            row["Username"] = eachUser.Rows[0][0];
            row["Days present"] = eachUser.Rows[0][1];
            row["Days absence"] = eachUser.Rows[0][2];
            row["Number of MAC"] = eachUser.Rows[0][3];
            //add row to database
            allUserOverviewTB.Rows.Add(row);
        }
        //return table
        return allUserOverviewTB;

    }
    /// <summary>
    /// get detail information of all users in a date
    /// </summary>
    /// <param name="day"></param>
    /// <returns></returns>
    [WebMethod(Description = "Get detail information of all users in a date. ")]
    public DataTable GetDetailInformationOfAllUsersInADay(DateTime day)
    {
        //create a datatable for hold data
        DataTable tb = new DataTable();
        //Add column to database
        tb.TableName = "GetUserInfoDetailInDay";
        tb.Columns.Add("Full name");
        tb.Columns.Add("Username");
        tb.Columns.Add("FU");
        tb.Columns.Add("status");
        tb.Columns.Add("time");
        tb.Columns.Add("MACaddress");
        tb.Columns.Add("Note");
        //create a temp datatable for hold data from function 'GetAllUsersAtRTD'
        //function 'GetAllUsersAtRTD' return a table with 
        // UserID FullName UserName FU      
        DataTable UsersAtRTD = GetAllUsersAtRtd();
        //Browse all rows of above datatable
        for (int i = 0; i < UsersAtRTD.Rows.Count; i++)
        {
            //do
            try
            {
                //Create a temp variable and assign to it with value from Row
                String Usercheck = UsersAtRTD.Rows[i][2].ToString();
                //create a temp datatable to hold value from function 'GetUserInfoDetailInDay'
                //function 'GetUserInfoDetailInDay' return a table with
                //Username | Status | time | MACaddress | Note
                DataTable userCheckDetalTB = GetUserInfoDetailInDay(Usercheck, day);
                //create a new row to table 'Tb', for using after
                DataRow r = tb.NewRow();
                //in new row, assign value to each column 
                r["Full name"] = UsersAtRTD.Rows[i][1].ToString();
                r["Username"] = userCheckDetalTB.Rows[0]["Username"];
                r["FU"] = UsersAtRTD.Rows[i][3];
                r["status"] = userCheckDetalTB.Rows[0]["status"];
                r["time"] = userCheckDetalTB.Rows[0]["time"];
                r["MACaddress"] = userCheckDetalTB.Rows[0]["MACaddress"];
                r["Note"] = userCheckDetalTB.Rows[0]["Note"];
                //Do task
                tb.Rows.Add(r);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
        //return table 
        return tb;
    }

    /// <summary>
    /// get all users in this week
    /// </summary>
    /// <returns></returns>
    [WebMethod(Description = "Get all users info in this Week: Username; status of days")]
    public DataTable GetInformationOfAllUsersInThisWeek()
    {
        //Gets the day of the week represented by this instance.
        int dayOfWeek = (int)DateTime.Now.DayOfWeek;
        //the date begin current week
        DateTime beginWeek = DateTime.Now.AddDays(-dayOfWeek);
        //the date at the end of current week
        DateTime endWeek = beginWeek.AddDays(6);
        //Create a temp table
        DataTable AllUsersInfoInThisWeek = new DataTable();
        //Add name for table
        AllUsersInfoInThisWeek.TableName = "AllUsersInfoInThisWeek";
        // add Columns Name
        AllUsersInfoInThisWeek.Columns.Add("Full name");
        AllUsersInfoInThisWeek.Columns.Add("Username");
        AllUsersInfoInThisWeek.Columns.Add(beginWeek.DayOfWeek.ToString());
        AllUsersInfoInThisWeek.Columns.Add(beginWeek.AddDays(1).DayOfWeek.ToString());
        AllUsersInfoInThisWeek.Columns.Add(beginWeek.AddDays(2).DayOfWeek.ToString());
        AllUsersInfoInThisWeek.Columns.Add(beginWeek.AddDays(3).DayOfWeek.ToString());
        AllUsersInfoInThisWeek.Columns.Add(beginWeek.AddDays(4).DayOfWeek.ToString());
        AllUsersInfoInThisWeek.Columns.Add(beginWeek.AddDays(5).DayOfWeek.ToString());
        AllUsersInfoInThisWeek.Columns.Add(beginWeek.AddDays(6).DayOfWeek.ToString());
        //create a table for hold information from 'GetUsersAtRTD'
        //function 'GetUsersAtRTD' return a table with columns:
        //// UserID | FullName | UserName | FU 
        DataTable userList = serviceForHainfo.GetUsersAtRtd();
        //clear table
        AllUsersInfoInThisWeek.Rows.Clear();
        //browse all user
        for (int i = 0; i < userList.Rows.Count; i++)
        {
            //Create a temp datarow, it's on behalf of each row of table 'AllUsersInfoInThisWeek'
            DataRow r = AllUsersInfoInThisWeek.NewRow();
            //Add fullname
            r[0] = userList.Rows[i][1];
            //add username
            r[1] = userList.Rows[i][2];
            //create a temp table 'dt' and give it a parameter (username)
            //then take another values - status of Monday-> Sunday 
            DataTable dt = GetUserInfoInThisWeek(userList.Rows[i][2].ToString());
            //if dt has values
            if (dt != null)
            {
                //assign for sunday
                r[2] = dt.Rows[0][1];
                //assign for monday
                r[3] = dt.Rows[0][2];
                //assign for tuesday
                r[4] = dt.Rows[0][3];
                //assign for wednesday
                r[5] = dt.Rows[0][4];
                //assign for thusday
                r[6] = dt.Rows[0][5];
                //assign for friday
                r[7] = dt.Rows[0][6];
                //assign for saturday
                r[8] = dt.Rows[0][7];
                //add row to table
                AllUsersInfoInThisWeek.Rows.Add(r);
            }
            else
            {
                //Returns a System.String that represents the current System.Object.
                userList.Rows[i][2].ToString();
            }
        }
        //return table
        return AllUsersInfoInThisWeek;

    }



    //================================GETALLUSERSINFOINTIME==========================
    //Return a table look likes this:
    //Full name	     Username	FU	    10/17/2011	 10/18/2011	 10/19/2011	     10/20/2011
    //Bùi Tường Thi	  ThiBT	   FU.K4c	  8:36 AM	   8:49 AM	   8:33 AM	       8:16 AM	
    /// <summary>
    /// get information of all user in period of time
    /// </summary>
    /// <param name="fr"></param>
    /// <param name="to"></param>
    /// <returns></returns>
    [WebMethod(Description = "Get Information of all user in period of time")]
    public DataTable GetInformationOfAllUsersInperiodOfTime(DateTime fr, DateTime to)
    {
        //if date's not in an right order
        if ((to - fr).TotalDays < 0)
        {
            //start swap
            DateTime d = fr;
            fr = to;
            to = d;
        }
        //create a temp table that hold a view 
        // UserID | FullName | UserName | FU  
        DataTable allUserTB = GetAllUsersAtRtd().Copy();
        //count the number of dates
        int numberDay = (int)(to - fr).TotalDays;
        //create a temp table to return when finished
        DataTable resutTB = new DataTable();
        //Assign name for table
        resutTB.TableName = "GetAllUsersInfoInTime";
        //add column to table
        resutTB.Columns.Add("Full name");
        //add column to table
        resutTB.Columns.Add("Username");
        //add column to table
        resutTB.Columns.Add("FU");
        //for each day
        for (int i = 0; i <= numberDay; i++)
        {
            //if current dates is not Saturday and Sunday
            if ((int)fr.AddDays(i).DayOfWeek != 0 && (int)fr.AddDays(i).DayOfWeek != 6)
            {
                //Add current date (in short format, such as '10/17/2011') to table 
                resutTB.Columns.Add(fr.AddDays(i).ToShortDateString());
            }

        }
        //with all users in column
        for (int i = 0; i < allUserTB.Rows.Count; i++)
        {
            //create a new row 
            DataRow r = resutTB.NewRow();
            //add fullname to first column of row
            r[0] = allUserTB.Rows[i][1].ToString();
            //add username to second column of row
            r[1] = allUserTB.Rows[i][2].ToString();
            //add batch to third column of row
            r[2] = allUserTB.Rows[i][3];
            //date number, posroll = 3 (4th column), show status of user at the first date. 
            //
            int posroll = 3;
            //with all days in table
            for (int j = 0; j <= numberDay; j++)
            {
                //when date not in Sunday or Saturday
                if ((int)fr.AddDays(j).DayOfWeek != 0 && (int)fr.AddDays(j).DayOfWeek != 6)
                {
                    //create a temp datatable with parameters:  username + date
                    //table return looks like this:
                    //Username	| status | time	| MACaddress | Note
                    DataTable atDayTB = GetUserInfoDetailInDay(allUserTB.Rows[i][2].ToString(), fr.AddDays(j));
                    //if time is null
                    if ((atDayTB.Rows[0]["time"]).ToString().Trim().Equals(""))
                    {
                        //mean that date, there no checking by user -> absence
                        r[posroll] = "Absence";
                        //increase by 1 to check the next date
                        posroll = posroll + 1;
                    }
                    //User has checked that date
                    else
                    {
                        //Get date and parsing it
                        DateTime d = DateTime.Parse((atDayTB.Rows[0]["time"]).ToString());
                        //in format looks like this:  8:36 AM
                        r[posroll] = d.ToShortTimeString();
                        //increase by 1 to check the next date
                        posroll = posroll + 1;
                    }
                }

            }
            //add row to table
            resutTB.Rows.Add(r);
        }
        //return table
        return resutTB;
    }
    /// <summary>
    /// get information of a user in this week
    /// </summary>
    /// <param name="userCheck"></param>
    /// <returns></returns>
    [WebMethod(Description = "Get infomation of A User in this week")]
    public DataTable GetInformationOfAUserInThisWeek(String userCheck)
    {
        //get ID of username
        long userID = serviceForHainfo.GetUserId(userCheck);
        //Gets the day of the week
        int dayOfWeek = (int)DateTime.Now.DayOfWeek;
        //First date of week
        DateTime beginWeek = DateTime.Now.AddDays(-dayOfWeek);
        //End date of week
        DateTime endWeek = beginWeek.AddDays(6);
        //temp table to hold values
        DataTable UserInfoInThisWeekTB = new DataTable();
        //Add table name
        UserInfoInThisWeekTB.TableName = "UserInfoInThisWeekTB";
        //Add Username Column 
        UserInfoInThisWeekTB.Columns.Add("Username");
        //Add All Datecolummn to table 
        UserInfoInThisWeekTB.Columns.Add(beginWeek.DayOfWeek.ToString());
        UserInfoInThisWeekTB.Columns.Add(beginWeek.AddDays(1).DayOfWeek.ToString());
        UserInfoInThisWeekTB.Columns.Add(beginWeek.AddDays(2).DayOfWeek.ToString());
        UserInfoInThisWeekTB.Columns.Add(beginWeek.AddDays(3).DayOfWeek.ToString());
        UserInfoInThisWeekTB.Columns.Add(beginWeek.AddDays(4).DayOfWeek.ToString());
        UserInfoInThisWeekTB.Columns.Add(beginWeek.AddDays(5).DayOfWeek.ToString());
        UserInfoInThisWeekTB.Columns.Add(beginWeek.AddDays(6).DayOfWeek.ToString());
        //If exiest a userID with username parameter 
        if (userID > 0)
        {
            //temp new row for hold data
            DataRow newrow = UserInfoInThisWeekTB.NewRow();
            //Add username to column Username in current row
            newrow["Username"] = userCheck;
            //browse all dates in this week
            for (int i = 0; i <= dayOfWeek; i++)
            {
                //create temp for get data from function 'GetUserInfoDetailInDay'
                //this 'GetUserInfoDetailInDay' return table look likes
                //Username	status	  time                 	MACaddress	   Note
                // thibt	Present	10/28/2011 7:59:13 AM	001EECBEB9D9	 
                DataTable UserInfoDetailInDay = GetUserInfoDetailInDay(userCheck, beginWeek.AddDays(i));
                //if that date, user've not check attendance
                if (UserInfoDetailInDay.Rows[0]["time"].ToString().Trim().Equals(""))
                {
                    //Add status of this date get from function 'UserInfoDetailInDay'
                    newrow[(i + 1)] = UserInfoDetailInDay.Rows[0]["status"];
                }
                else
                {
                    //Add time log
                    newrow[(i + 1)] = UserInfoDetailInDay.Rows[0]["time"];
                }
            }
            //add new row to that table
            UserInfoInThisWeekTB.Rows.Add(newrow);
        }
        //return table
        return UserInfoInThisWeekTB;
    }



}
